package com.atguigu.product.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;

/**
 * @author Jia Fa
 * @create 2021-12-09 10:16
 */
//@Configuration
@Slf4j
public class RabbitMQConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct   // @PostConstruct方法将在最后生成Bean的时候被调用  构造器之后执行
    public void init(){
        // 确认消息是否到达交换机
        this.rabbitTemplate.setConfirmCallback((@Nullable CorrelationData correlationData, boolean ack, @Nullable String cause)->{
            if (ack){
//                System.out.println("消息已到达,走你");
                log.warn("消息已到达{}",correlationData);
            }else {
                log.warn("消息丢失,丢失消息为 {},原因 {}",correlationData,cause);
            }
        });
        // 确认消息是否到达队列   只有消息没有到达才会执行
        this.rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey)->{
            log.warn("消息未到达对垒,交换机{},路由键{},内容{}",exchange,routingKey,new String(message.getBody()));
        });
    }

    // 死信队列
    @Bean
    public Queue deadQueue(){
        return QueueBuilder.durable("SPRING_DEAD_QUEUE").build();
    }

    // 死信交换机
    @Bean
    public Exchange deadExchange(){
        return ExchangeBuilder.topicExchange("SPRING_DEAD_EXCHANGE").durable(true).build();
    }

    // 绑定死信
    @Bean

    public Binding deadBinding(Queue deadQueue,Exchange deadExchange){
        // 绑定时指定routingKing
        return BindingBuilder.bind(deadQueue).to(deadExchange).with("dead_key").noargs();
    }

    // 延时队列  需要创建时指定死信交换机
    @Bean
    public Queue delayQueue(){
        return QueueBuilder.durable("SPRING_DELAY_QUEUE").deadLetterExchange("SPRING_DEAD_EXCHANGE").deadLetterRoutingKey("dead_key").ttl(60000).build();
    }

    // 延时交换机
    @Bean
    public Exchange delayExchange(){
        return ExchangeBuilder.topicExchange("SPRING_DELAY_EXCHANGE").durable(true).build();
    }

    // 延时交换机绑定延时队列
    @Bean
    public Binding delayBinding(Queue delayQueue,Exchange delayExchange){
        return BindingBuilder.bind(delayQueue).to(delayExchange).with("delay_key").noargs();
    }

}
